import "ol/ol.css";
import * as ol from "ol";
import { Map, View } from "ol";
import Tile from "ol/layer/Tile";
import OSM from "ol/source/OSM";
import { Style, Circle, Stroke, Fill, Text, Icon } from "ol/style";
import layerVector from "ol/layer/Vector";
import sourceVector from "ol/source/Vector";
import Cluster from "ol/source/Cluster";
import Point from "ol/geom/Point";
import Feature from "ol/Feature";
import SourceVector from "ol/source/Vector";
import Draw, { createRegularPolygon, createBox } from "ol/interaction/Draw";
import LayerVector from "ol/layer/Vector";
import Polygon from "ol/geom/Polygon";
import LineString from "ol/geom/LineString";
import iconPng from "@/assets/images/icon.png"; // 引入图标图片
// 添加图标
function getIconvectorLayer(point) {
  // 1、创建图标
  let iconFeature = new Feature({
    geometry: new Point(point), // 图标展示的位置
    population: 4000,
    rainfall: 500,
  });
  // 2、创建图标样式
  let iconStyle = new Style({
    image: new Icon({
      // 定义图标锚点
      anchor: [0.5, 46], // 根据图标的大小，对应上面 [0, 0] 的坐标
      anchorXUnits: "fraction",
      anchorYUnits: "pixels",
      // 图标所使用的图片文件
      // src: require('../../assets/images/icon.png')
      // 或者
      src: iconPng,
    }),
  });
  // 3、把样式应用到图标上
  iconFeature.setStyle(iconStyle);
  var iconsource = new SourceVector({
    features: [iconFeature],
  });
  var iconvectorLayer = new LayerVector({
    source: iconsource,
    name: "imgLayer",
  });
  return iconvectorLayer;
}
function getColorIconFeatureLayer(point) {
  let madrid = new Feature({
    geometry: new Point(point),
  });
  madrid.setStyle(
    new Style({
      image: new Icon({
        color: [113, 140, 0],
        crossOrigin: "anonymous",
        src: require("../assets/images/dot.png"),
      }),
    })
  );
  let vectorSource = new SourceVector({
    features: [madrid],
  });

  let vectorLayer = new LayerVector({
    source: vectorSource,
    name: "colorLayer",
  });
  return vectorLayer
}
// 创建图标要素
function getIconFeature(point) {
  // 1、创建图标
  let iconFeature = new Feature({
    geometry: new Point(point), // 图标展示的位置
    population: 4000,
    rainfall: 500,
  });
  // 2、创建图标样式
  let iconStyle = new Style({
    image: new Icon({
      // 定义图标锚点
      anchor: [0.5, 46], // 根据图标的大小，对应上面 [0, 0] 的坐标
      anchorXUnits: "fraction",
      anchorYUnits: "pixels",
      // 图标所使用的图片文件
      // src: require('../../assets/images/icon.png')
      // 或者
      src: iconPng,
    }),
  });
  // 3、把样式应用到图标上
  iconFeature.setStyle(iconStyle);
  return iconFeature;
}
// 生成聚合图层
function getPolymerizatioLayer() {
  let count = 800; // 点的数量
  let features = []; // 存放点要素的数组

  // 初始化每个点的坐标位置
  let e = [116.1994204738591, 39.80275939942994];
  for (let i = 0; i < count; ++i) {
    let coordinates = [
      e[0] * (1 + Math.random() / 1000),
      e[1] * (1 + Math.random() / 1000),
    ];
    console.log("coordinates", coordinates);
    // 根据坐标生成点状几何
    features[i] = new Feature(new Point(coordinates));
  }
  console.log("features", features);
  // 把点状要素放到矢量源里
  let source = new sourceVector({
    features,
  });

  let clusterSource = new Cluster({
    // 通过 distance 来控制两个点聚合的间距，如果2个点的间距小于 distance 所设置的数时，就会以聚合的方式显示
    distance: 0.5,
    source, // 就是前面用到的矢量数据源
  });

  // 点的样式
  let styleCache = {};
  let PolymerizatioLayer = new layerVector({
    name: "polymerization",
    source: clusterSource, // 源，指向上面的聚合数据源
    style: (feature) => {
      // feature 是聚合后的数据，每一个 feature 代表距离小于上面设置的点状要素
      let size = feature.get("features").length; // features 是点状要素
      let style = styleCache[size];
      if (!style) {
        style = new Style({
          image: new Circle({
            radius: 10,
            stroke: new Stroke({
              color: "#fff",
            }),
            fill: new Fill({
              color: "#3399cc",
            }),
          }),
          text: new Text({
            text: size.toString(), // 以聚合点的数量作为显示的内容
            fill: new Fill({
              color: "#fff",
            }),
          }),
        });

        styleCache[size] = style;
      }

      return style;
    },
  });

  return PolymerizatioLayer;
}
// 画点
function DrawFn(val, isFreehand = false, isArrow) {
  var geometryFunction;
  console.log("val", val);
  if (val === "Square") {
    console.log(111);
    // 方形
    geometryFunction = createRegularPolygon(4);
  } else if (val === "Rectangle") {
    // 矩形
    geometryFunction = createBox();
  } else if (val === "Hexagram") {
    geometryFunction = function (coordinates, geometry) {
      //中心点
      var center = coordinates[0];
      //鼠标点击的另一个点
      var last = coordinates[1];
      var dx = center[0] - last[0];
      var dy = center[1] - last[1];
      //半径
      var radius = Math.sqrt(dx * dx + dy * dy);
      //旋转的角度
      var rotation = Math.atan2(dy, dx);
      //用来记录顶点坐标的数组
      var newCoordinates = [];
      //顶点个数
      var numPoints = 12;
      for (var i = 0; i < numPoints; ++i) {
        //顶点相对转过的角度
        var angle = rotation + (i * 2 * Math.PI) / numPoints;
        //确定凸顶点和凹顶点
        var fraction = i % 2 === 0 ? 1 : 0.58;
        //计算顶点的坐标
        var offsetX = radius * fraction * Math.cos(angle);
        var offsetY = radius * fraction * Math.sin(angle);
        newCoordinates.push([center[0] + offsetX, center[1] + offsetY]);
      }
      newCoordinates.push(newCoordinates[0].slice());
      if (!geometry) {
        geometry = new Polygon([newCoordinates]);
      } else {
        geometry.setCoordinates([newCoordinates]);
      }
      return geometry;
    };
  }
  var source = new SourceVector({
    wrapX: false, // 禁止横向无限重复（底图渲染的时候会横向无限重复），设置了这个属性，可以让绘制的图形不跟随底图横向无限重复
  });
  var styles;
  if (isArrow == "arrow") {
    styles = styleFunction;
  }
  var vector = new LayerVector({
    style: styles,
    source: source,
  });
  var draw = ["Square", "Rectangle", "Hexagram"].includes(val)
    ? new Draw({
        source,
        type: "Circle",
        geometryFunction,
      })
    : new Draw({
        source,
        type: val,
        freehand: isFreehand,
      });
  return { vector, draw };
}
// 设置带箭头的线段
function styleFunction(feature) {
  let geometry = feature.getGeometry();
  let styles = [
    new Style({
      stroke: new Stroke({
        color: "#ffcc33",
        width: 2,
      }),
    }),
  ];
  geometry.forEachSegment((start, end) => {
    let dx = end[0] - start[0];
    let dy = end[1] - start[1];
    let rotation = Math.atan2(dy, dx);
    styles.push(
      new Style({
        geometry: new Point(end),
        image: new Icon({
          src: require("@/assets/images/arrow.png"),
          anchor: [0.75, 0.5],
          rotateWithView: true,
          rotation: -rotation,
        }),
      })
    );
  });
  return styles;
}
// 由坐标点画线
function drawLineFromPoint(pointsList) {
  var roadLine = new LineString(pointsList);
  var roadLineSource = new SourceVector({
    features: [new Feature(roadLine)],
  });
  var roadLineLayer = new LayerVector({
    source: roadLineSource,
    name:"drawLineFromPoint",
    style: new Style({
      stroke: new Stroke({
        color: "red",
        width: 3,
      }),
    }),
  });
  return roadLineLayer;
}
// 由坐标点画面
function drawPolygonFromPoint(points) {
  console.log("points", points);
  var polygon = new Polygon([points]);
  var polygonSource = new SourceVector({
    features: [new Feature(polygon)],
    wrapX: false,
  });
  var vectorLayer = new LayerVector({
    source: polygonSource,
    name:"drawPolygonFromPoint",
    style: new Style({
      stroke: new Stroke({
        color: "red",
        width: 3,
      }),
      fill: new Fill({
        color: "rgba(0, 0, 255, 0.1)",
      }),
    }),
  });

  return vectorLayer;
}
function flyTo(location, done = () => {}) {
  let view = this.map.getView();
  let duration = 2000;
  let zoom = view.getZoom();
  let parts = 2;
  let called = false;
  function callback(complete) {
    --parts;
    if (called) {
      return;
    }
    if (parts === 0 || !complete) {
      called = true;
      done(complete);
    }
  }
  view.animate(
    {
      center: location,
      duration: duration,
    },
    callback
  );
  view.animate(
    {
      zoom: zoom - 1,
      duration: duration / 2,
    },
    {
      zoom: zoom,
      duration: duration / 2,
    },
    callback
  );
}
// 弹跳动画
function bounce(t) {
  let s = 7.5625;
  let p = 2.75;
  let l;
  if (t < 1 / p) {
    l = s * t * t;
  } else {
    if (t < 2 / p) {
      t -= 1.5 / p;
      l = s * t * t + 0.75;
    } else {
      if (t < 2.5 / p) {
        t -= 2.25 / p;
        l = s * t * t + 0.9375;
      } else {
        t -= 2.625 / p;
        l = s * t * t + 0.984375;
      }
    }
  }
  return l;
}
// 根据name属性删除对应的图层
function getLayerFromName(map, name) {
  var res = false;
  for (let i = 0; i < map.getLayers().getProperties().length; i++) {
    if (map.getLayers().item(i).getProperties().name == name) {
      res = map.getLayers().item(i);
    }
  }
  return res;
}
export {
  getIconvectorLayer,
  getColorIconFeatureLayer,
  getIconFeature,
  getPolymerizatioLayer,
  DrawFn,
  drawLineFromPoint,
  drawPolygonFromPoint,
  flyTo,
  bounce,
  getLayerFromName,
};
